package de.hach.manno;

import java.util.Calendar;
import java.util.List;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import de.hach.manno.webservice.Club;
import de.hach.manno.webservice.Event;
import de.hach.manno.webservice.MannOWebservice;
import de.hach.manno.webservice.Match;
import de.hach.manno.webservice.Player;
import de.hach.manno.webservice.PlaysFor;

/**
 * Service will automatically download changes from WebService
 * 
 * @author hanspeter
 * @version 1.0
 * @since 16/06/2012
 */
public class UpdaterService extends Service {
	private static final String TAG = "UpdaterService";
	static final int DELAY = 1 * 60 * 1000; // wait 1 Minute
	private boolean runFlag = false;
	private Updater updater;
	private MannOApplication mannO;
	private MannOData mannOData;

	private static final String NEW_DATA_INTENT = "de.hach.manno.NEW_DATA";
	private static final String NEW_DATA_EXTRA_COUNT = "de.hach.manno.NEW_DATA_COUNT";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mannO = (MannOApplication) getApplication();
		updater = new Updater();
		mannOData = mannO.getMannOData();
		Log.d(TAG, "onCreate");
	}

	@Override
	public int onStartCommand(Intent intent, int flag, int startId) {
		if (!runFlag) {
			runFlag = true;
			updater.start();
			mannO.setServiceRunning(true);
			Log.d(TAG, "onStarted");
		}
		return Service.START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		runFlag = false;
		updater.interrupt();
		updater = null;
		mannO.setServiceRunning(false);
		Log.d(TAG, "onDestroy");
	}

	private class Updater extends Thread {
		Intent intent;

		public Updater() {
			super("UpdaterService-Updater");
		}

		@Override
		public void run() {
			Calendar lastUpdate;
			UpdaterService updaterService = UpdaterService.this;

			// TODO Initialize Webservice using user and password
			MannOWebservice mannOWebservice = new MannOWebservice();

			while (updaterService.runFlag) {
				try {
					Log.d(TAG, "Updater running");
					// Calendar object containing timestamp of latest update in
					// database
					lastUpdate = mannOData.getLatestUpdate();
					// Check most recent timestamp of tables in WebService
					boolean[] status = mannOWebservice.getStatus(lastUpdate);
					int newUpdates = 0;
					if (status != null) {
						if (status[0]) {
							Log.d(TAG, "Update Clubs");
							List<Club> clubList = mannOWebservice
									.getClubUpdates(lastUpdate);
							Log.d(TAG, clubList.size() + " clubs found");
							mannOData.writeClubsToDatabase(clubList);
							newUpdates++;
						}
						if (status[1]) {
							Log.d(TAG, "Update Event");
							List<Event> eventList = mannOWebservice
									.getEventUpdates(lastUpdate);
							Log.d(TAG, eventList.size() + " events found");
							mannOData.writeEventsToDatabase(eventList);
							newUpdates++;
						}
						if (status[2]) {
							Log.d(TAG, "Update Match");
							List<Match> matchList = mannOWebservice
									.getMatchUpdates(lastUpdate);
							Log.d(TAG, matchList.size() + " matches found");
							mannOData.writeMatchesToDatabase(matchList);
							newUpdates++;
						}
						if (status[3]) {
							Log.d(TAG, "Update Player");
							List<Player> playerList = mannOWebservice
									.getPlayerUpdates(lastUpdate);
							Log.d(TAG, playerList.size() + " players found");
							mannOData.writePlayersToDatabase(playerList);
							newUpdates++;
						}
						if (status[4]) {
							Log.d(TAG, "Update PlaysFor");
							List<PlaysFor> playsForList = mannOWebservice
									.getPlaysForUpdates(lastUpdate);
							Log.d(TAG, playsForList.size() + " players found");
							mannOData.writePlaysForToDatabase(playsForList);
							newUpdates++;
						}
						if (newUpdates > 0) {
							intent = new Intent(NEW_DATA_INTENT);
							intent.putExtra(NEW_DATA_EXTRA_COUNT, newUpdates);
							updaterService.sendBroadcast(intent);
							Log.d(TAG, "send NEW_DATA_INTENT");
						}else{
							Log.d(TAG,"Nothing to update");
						}

					} else {
						Log.d(TAG, "Error getting status from Webservice");
					}
					Log.d(TAG, "Updater ran");
					Thread.sleep(DELAY);
				} catch (InterruptedException ie) {
					Log.e(TAG, ie.getMessage());
					updaterService.runFlag = false;
				}
			}
		}
	}// Updater

}
